var needle = require('needle');
needle.defaults({
    open_timeout: 1000 * 20,
    user_agent: 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_11_6) '
        + 'AppleWebKit/537.36 (KHTML, like Gecko) Chrome/51.0.2704.106 Safari/537.36'
});
var needleMethod = ['post', 'get', 'head', 'put', 'request', 'patch'];
var proxy = {};
needleMethod.forEach(function(name) {
    proxy[name] = function () {
        var args = [];
        for(var i=0;i<arguments.length;i++){
            args.push(arguments[i]);
        }
        return new Promise(function (resolve, reject) {
            args.push(function (err, res, body) {
                if (err) {
                    reject(err);
                    return;
                }
                var opt = args[args.length - 2];
                if (opt && opt.parseJson && body) {
                    resolve(JSON.parse(body));
                } else if (opt.multiReturn) {
                    resolve({
                        res,
                        body
                    });
                } else {
                    resolve(body);
                }
            });
            // console.log('do req:', args);
            needle[name].apply(needle, args);
        });
    };
});

module.exports = proxy;
